package edu.gdut.tiantian.dao;


import java.util.List;
import java.util.Map;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Many;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.SelectKey;
import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.mapping.FetchType;
import org.springframework.stereotype.Repository;

import edu.gdut.tiantian.entity.User;

@Repository
public interface UserDao {

	@Select("select * from users where username=#{username} and password=#{password}")
	User userLogin(@Param("username")String username,@Param("password")String password);
	
	@SelectKey(before = true,keyColumn = "id",keyProperty = "id",statement = "select replace(uuid(),'-','')", resultType = String.class)
	@Insert("insert into users(id,username,password,mobile,email,sex,birthday) values("
			+ "#{id},#{username},#{password},#{mobile},#{email},#{sex},#{birthday})")
	void save(User user);
	
	@Update("update users set username=#{username},mobile=#{mobile},email=#{email},sex=#{sex},birthday=#{birthday} where id=#{id}")
	void updateUser(User user);
	
	@Select("select * from users where username=#{username}")
	User findByUsername(String username);
	
	@Update("update users set status=#{status} where id=#{userId}")
	void  updateStatus(@Param("userId")String userId,@Param("status")Integer status);
	
	@Select("select * from users where id=#{userId}")
	User findById(String userId);
	
	@Select("select * from users where id=#{userId} ")
	@Results({
		@Result(id = true,property="id",column="id"),
		@Result(property="username",column="username"),
		@Result(property="email",column="email"),
		@Result(property="mobile",column="mobile"),
		@Result(property="status",column="status"),
		@Result(property="sex",column="sex"),
		@Result(property="orders",column="id",many=@Many(select="edu.gdut.tiantian.dao.OrderDao.findByUserId",fetchType = FetchType.EAGER)),
		@Result(property="cartItems",column="id",many =  @Many(select="edu.gdut.tiantian.dao.CartDao.getCart",fetchType = FetchType.EAGER))
	})
	User getUser(String userId);
	
	//条件查询
	@Select("<script> select * from users where 1=1 "
			+ "<foreach collection='condition' index='keys' item='values'>"
			+ "<if test='keys == " +"\"username\" and keys != null" +"'>and username like CONCAT('%',#{values},'%')</if>"
			+ "<if test='keys == " +"\"userId\" and keys != null" +"'>and id like CONCAT('%',#{values},'%')</if>"
			+ "<if test='keys == " +"\"status\" and keys != null and values!=-1" +"'>and status=#{values}</if>"
			+ "</foreach>"
			+ "</script>")
	@Results({
		@Result(property = "category",column = "categoryId",one = @One(select="edu.gdut.tiantian.dao.CategoryDao.findById"))
	})
	List<User> findByCondition(@Param("condition")Map<String,String> condition);
}
